package com.mdlib.helper.module.send.order.fragments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ljlib.core.util.EmptyUtils;
import com.ljlib.core.util.common.TimeUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.common.MDConstant;
import com.mdlib.helper.event.AgecyEvent;
import com.mdlib.helper.event.MoneyEvent;
import com.mdlib.helper.event.PhoneEvent;
import com.mdlib.helper.event.TimeEvent;
import com.mdlib.helper.event.VoucherEvent;
import com.mdlib.helper.model.AppModel;
import com.mdlib.helper.model.entity.OneKeyServiceEntity;
import com.mdlib.helper.model.entity.OrderIdInfo;
import com.mdlib.helper.model.entity.ServiceMoney;
import com.mdlib.helper.model.entity.VoucherEntity;
import com.mdlib.helper.module.location.AddressEntity;
import com.mdlib.helper.module.location.MapActivity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：HQY on 16/11/22 15:02
 * 邮箱：hqy_xz@126.com
 * <p>
 * 代办
 */

public class AgencyFragment extends BaseTitleFragment {


    @Bind(R.id.et_describe)
    EditText mEtDescribe;
    @Bind(R.id.rl_agency_describe)
    RelativeLayout mRlAgencyDescribe;
    @Bind(R.id.iv_shopping_address)
    ImageView mIvShoppingAddress;
    @Bind(R.id.iv_minnetoka_back_one)
    ImageView mIvMinnetokaBackOne;
    @Bind(R.id.rl_agency_type)
    RelativeLayout mRlAgencyType;
    @Bind(R.id.iv_delivery_address)
    ImageView mIvDeliveryAddress;
    @Bind(R.id.iv_minnetoka_back_two)
    ImageView mIvMinnetokaBackTwo;
    @Bind(R.id.rl_delivery_address)
    RelativeLayout mRlDeliveryAddress;
    @Bind(R.id.iv_success_time)
    ImageView mIvSuccessTime;
    @Bind(R.id.iv_minnetoka_back_three)
    ImageView mIvMinnetokaBackThree;
    @Bind(R.id.tv_agency_time)
    TextView mTvAgencyTime;
    @Bind(R.id.rl_success_time)
    RelativeLayout mRlSuccessTime;
    @Bind(R.id.iv_harves_phone)
    ImageView mIvHarvesPhone;
    @Bind(R.id.iv_minnetoka_back_four)
    ImageView mIvMinnetokaBackFour;
    @Bind(R.id.tv_agency_phone)
    TextView mTvAgencyPhone;
    @Bind(R.id.rl_agency_phone)
    RelativeLayout mRlAgencyPhone;
    @Bind(R.id.iv_service_money)
    ImageView mIvServiceMoney;
    @Bind(R.id.iv_minnetoka_back_five)
    ImageView mIvMinnetokaBackFive;
    @Bind(R.id.tv_agency_money)
    TextView mTvAgencyMoney;
    @Bind(R.id.rl_service_money)
    RelativeLayout mRlServiceMoney;
    @Bind(R.id.iv_agency_voucher)
    ImageView mIvAgencyVoucher;
    @Bind(R.id.iv_minnetoka_back_six)
    ImageView mIvMinnetokaBackSix;
    @Bind(R.id.tv_agency_voucher)
    TextView mTvAgencyVoucher;
    @Bind(R.id.rl_agency_voucher)
    RelativeLayout mRlAgencyVoucher;
    @Bind(R.id.tv_pay_money)
    TextView mTvPayMoney;
    @Bind(R.id.tv_pay_submit)
    TextView mTvPaySubmit;
    @Bind(R.id.tv_agecy_name)
    TextView mTvAgecyName;
    @Bind(R.id.tv_send_addr)
    TextView mTvSendAddr;
    @Bind(R.id.tv_get_phone)
    TextView mTvGetPhone;
    @Bind(R.id.tv_service_money)
    TextView mTvServiceMoney;

    private long timestamp = 0;
    private String time;
    private ServiceMoney serviceMoney;

    private String remark;
    private String postAddr;
    private String getPhone;
    private String serviceMoneys;
    private String voucher;
    private String vouchers = "";
    private OneKeyServiceEntity mKeyService;
    private String mAgencyName;
    private String agecyId;
    private String agecyType;
    private String agencyLat;
    private String agencyLong;


    public static AgencyFragment newInstance(OneKeyServiceEntity serviceEntity, String type) {
        AgencyFragment fragment = new AgencyFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(UIHelper.AGENCY, serviceEntity);
        bundle.putString(UIHelper.AGENCY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isEmpty(getArguments())) {
            getActivity().finish();
        }
        mKeyService = (OneKeyServiceEntity) getArguments().getSerializable(UIHelper.AGENCY);
        if (mKeyService == null) {
            mKeyService=new OneKeyServiceEntity();
            mKeyService.setService_money("10");
        }
        agecyType = getArguments().getString(UIHelper.AGENCY_TYPE);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_agency;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setTitle(R.string.send_home_agency, R.color.white)
                .setTitleBgColor(R.color.generic_view_bg)
                .setImgLeftListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeFragment();
                    }
                });
        init();

    }

    public void init() {
        if (agecyType.equals(UIHelper.AGENCY_TYPE_TWO)) {
            mTvAgecyName.setText(mKeyService.getName());
            mTvAgencyMoney.setText("￥" + mKeyService.getService_money());
            mTvPayMoney.setText("￥" + mKeyService.getService_money());
            agecyId = mKeyService.getHandle_type();
            mRlAgencyType.setEnabled(false);
        } else if (agecyType.equals(UIHelper.AGENCY_TYPE_ONE)) {
            mTvAgecyName.setText(getActivity().getResources().getString(R.string.agency_tv_type));
            mTvAgencyMoney.setText("￥" + mKeyService.getService_money());
            mTvPayMoney.setText("￥" + mKeyService.getService_money());
            agecyId = mKeyService.getHandle_type();
            mRlAgencyType.setEnabled(true);
        }
        mTvAgencyPhone.setText(AppModel.getInstance().getAppInitEntity().getPhone());
    }


    @OnClick({R.id.rl_agency_type, R.id.rl_delivery_address, R.id.rl_success_time, R.id.rl_agency_phone, R.id.rl_service_money, R.id.rl_agency_voucher, R.id.tv_pay_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_agency_type:
                addFragment(AgecyTypeFragment.newInstance());
                break;
            case R.id.rl_delivery_address:
                UIHelper.showMapPage(getActivity(), UIHelper.MAP_TYPE_THREE, UIHelper.TAKE);
                break;
            case R.id.rl_success_time:
                UIHelper.showSuccessTime(getActivity());
                break;
            case R.id.rl_agency_phone:
                UIHelper.showModifyPHone(getActivity(), mTvAgencyPhone.getText().toString(), UIHelper.AGENCY);
                break;
            case R.id.rl_service_money:
                if (mKeyService != null) {
                    serviceMoney = new ServiceMoney();
                    serviceMoney.setMinServiceMoney(Double.parseDouble(mKeyService.getService_money()));
                    serviceMoney.setMxServiceMoney(Double.parseDouble("1000"));
                    serviceMoney.setServiceMoneyStep(Double.parseDouble("1"));
                }
                UIHelper.showServiceMoney(getActivity(), serviceMoney);
                break;
            case R.id.rl_agency_voucher:
                getVoucher();
                break;
            case R.id.tv_pay_submit:
                remark = mEtDescribe.getText().toString();
                postAddr = mTvSendAddr.getText().toString();
                getPhone = mTvAgencyPhone.getText().toString();
                serviceMoneys = mTvAgencyMoney.getText().toString().substring(1, mTvAgencyMoney.getText().toString().length());
                voucher = mTvAgencyVoucher.getText().toString();
                if (EmptyUtils.isEmpty(remark)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.generic_et_not_empty));
                    return;
                }

                if (EmptyUtils.isEmpty(postAddr)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.generic_et_address_not_empty));
                    return;
                }
//
                if (EmptyUtils.isEmpty(getPhone)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.generic_et_phone_not_empty));
                    return;
                }

//                if (!EmptyUtils.isEmpty(voucher)) {
//                    vouchers = voucher.substring(1, voucher.length() - 3);
//                }
                orderAgency(remark, postAddr, getPhone, serviceMoneys, agencyLat, agencyLong, vouchers);
//                addFragment(OrdersFragment.newInstance());
                break;
        }
    }

    private void orderAgency(String remark, String sendAddr,
                             String getPhone, String money,
                             String lat, String length, String couponId) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .sendAgency(remark, timestamp + "", sendAddr, money, lat, length, agecyId, "1", MDConstant.PLATFORM,
                        getPhone, couponId)
                .compose(RxHelper.<OrderIdInfo>defaultHandleResult())
                .subscribe(new RxSubscribe<OrderIdInfo>() {
                    @Override
                    protected void onSucc(OrderIdInfo idInfo) {
                        UIHelper.showPayOrder(getActivity(), idInfo);
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }


    /**
     * 获取代金券
     */
    private void getVoucher() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getMyVoucher()
                .compose(RxHelper.<ArrayList<VoucherEntity>>defaultHandleResult())
                .subscribe(new RxSubscribe<ArrayList<VoucherEntity>>() {
                    @Override
                    protected void onSucc(ArrayList<VoucherEntity> voucherEntities) {
                        UIHelper.showDialogVoucher(getActivity(), voucherEntities);
                    }

                    @Override
                    protected void onFail(String msg) {

                    }
                })
        );
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == MapActivity.REQUEST_ADDRESS_CODE) {
            AddressEntity addressEntity = (AddressEntity) data.getSerializableExtra(MapActivity.EXTRA_ADDRESS_MAP);
            String mapType = data.getStringExtra(UIHelper.MAP_TYPE);
            if (mapType.equals(UIHelper.MAP_TYPE_THREE)) {
                mTvSendAddr.setText(addressEntity.getDetailAddress());
                agencyLat = String.valueOf(addressEntity.getLatitude());
                agencyLong = String.valueOf(addressEntity.getLongitude());
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AgecyEvent agecyEvent) {
        agecyId = String.valueOf(agecyEvent.getId());
        mAgencyName = agecyEvent.getName();
        mTvAgecyName.setText(mAgencyName);
        mTvAgencyMoney.setText("￥" + agecyEvent.getServiceMoney());
        mTvPayMoney.setText("￥" + agecyEvent.getServiceMoney());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MoneyEvent moneyEvent) {
        mTvAgencyMoney.setText(moneyEvent.getMoney());
        mTvPayMoney.setText(moneyEvent.getMoney());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(VoucherEvent voucherEvent) {
        vouchers=voucherEvent.getVoucherEntity().getId()+"";
        mTvAgencyVoucher.setText("￥" + voucherEvent.getVoucherEntity().getValue() + "代金券");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PhoneEvent phoneEvent) {
        mTvAgencyPhone.setText(phoneEvent.getPhone());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TimeEvent timeEvent) {
        time = TimeUtils.getCurTimeString(TimeUtils.SUCCESS_YEAR) + "." + timeEvent.getMonth() + " " + timeEvent.getHour();
        timestamp = TimeUtils.string2Milliseconds(time, TimeUtils.SUCCESS_MONTH) / 1000;
        if (timestamp == 0) {
            mTvAgencyTime.setText("尽快");
        } else {
            mTvAgencyTime.setText(time);
        }
    }


}
